/**
 * 音频管理工具类
 * 用于管理游戏音效和背景音乐
 */
class AudioManager {
    constructor() {
        // 音效集合
        this.sounds = {};
        
        // 背景音乐
        this.music = null;
        
        // 音量设置
        this.settings = {
            sfxVolume: 0.7,
            musicVolume: 0.5,
            muted: false
        };
        
        // 加载设置
        this.loadSettings();
        
        // 预加载音效
        this.preloadSounds();
    }
    
    /**
     * 加载音量设置
     */
    loadSettings() {
        const storage = new Storage();
        const settings = storage.getSettings();
        
        if (settings.sfxVolume !== undefined) {
            this.settings.sfxVolume = settings.sfxVolume;
        }
        
        if (settings.musicVolume !== undefined) {
            this.settings.musicVolume = settings.musicVolume;
        }
        
        if (settings.muted !== undefined) {
            this.settings.muted = settings.muted;
        }
    }
    
    /**
     * 保存音量设置
     */
    saveSettings() {
        const storage = new Storage();
        storage.saveSettings({
            sfxVolume: this.settings.sfxVolume,
            musicVolume: this.settings.musicVolume,
            muted: this.settings.muted
        });
    }
    
    /**
     * 预加载音效
     */
    preloadSounds() {
        // 定义音效 - 只保留已引入的音效
        const soundFiles = {
            typing: 'assets/audio/sfx/typing.mp3',
            error: 'assets/audio/sfx/error.wav',
            correct: 'assets/audio/sfx/click.mp3',
            start: 'assets/audio/sfx/start.mp3',
            success: 'assets/audio/sfx/success.mp3',
            background: 'assets/audio/music/background.mp3',
            startGame: 'assets/audio/music/playBgm.mp3'
        };
        
        // 由于资源可能还未准备好，这里只定义音效，不实际加载
        // 实际项目中应该在这里加载所有音效
        
        // 将所有音效添加到 sounds 对象中
        for (const [name, path] of Object.entries(soundFiles)) {
            this.sounds[name] = {
                name: name,
                path: path,
                howl: null
            };
        }
        
        // 预加载常用音效
        this.loadSound('correct');
        this.loadSound('error');
        this.loadSound('start');
        this.loadSound('background');
        this.loadSound('startGame');
    }
    
    /**
     * 加载单个音效
     * @param {string} name 音效名称
     * @returns {Promise} 加载完成的Promise
     */
    loadSound(name) {
        return new Promise((resolve, reject) => {
            const sound = this.sounds[name];
            
            if (!sound) {
                reject(new Error(`未找到音效: ${name}`));
                return;
            }
            
            if (sound.howl) {
                resolve(sound.howl);
                return;
            }
            
            sound.howl = new Howl({
                src: [sound.path],
                volume: this.settings.muted ? 0 : this.settings.sfxVolume,
                onload: () => resolve(sound.howl),
                onloaderror: (id, error) => reject(new Error(`加载音效失败: ${name}, 错误: ${error}`))
            });
        });
    }
    
    /**
     * 加载背景音乐
     * @returns {Promise} 加载完成的Promise
     */
    loadMusic() {
        return new Promise((resolve, reject) => {
            if (!this.music) {
                reject(new Error('未找到背景音乐'));
                return;
            }
            
            if (this.music.howl) {
                resolve(this.music.howl);
                return;
            }
            
            this.music.howl = new Howl({
                src: [this.music.path],
                volume: this.settings.muted ? 0 : this.settings.musicVolume,
                loop: true,
                onload: () => resolve(this.music.howl),
                onloaderror: (id, error) => reject(new Error(`加载背景音乐失败, 错误: ${error}`))
            });
        });
    }
    
    /**
     * 播放音效
     * @param {string} name 音效名称
     */
    playSound(name) {
        if (this.settings.muted) return;
        
        const sound = this.sounds[name];
        
        if (!sound) {
            console.warn(`未找到音效: ${name}`);
            return;
        }
        
        if (!sound.howl) {
            this.loadSound(name)
                .then(howl => howl.play())
                .catch(error => console.error(error));
            return;
        }
        
        sound.howl.play();
    }
    
    /**
     * 播放背景音乐
     * @param {string} name 音乐名称
     */
    playMusic(name) {
        if (this.settings.muted) return;
        
        console.log(`尝试播放音乐: ${name}`);
        
        const sound = this.sounds[name];
        
        if (!sound) {
            console.warn(`未找到音乐: ${name}`);
            return;
        }
        
        // 停止所有其他正在播放的音乐
        for (const [soundName, soundObj] of Object.entries(this.sounds)) {
            if (soundName !== name && soundObj.howl && soundObj.howl.playing()) {
                soundObj.howl.stop();
            }
        }
        
        if (!sound.howl) {
            console.log(`加载音乐: ${name}`);
            this.loadSound(name)
                .then(howl => {
                    console.log(`音乐加载成功: ${name}`);
                    howl.loop(true);
                    howl.volume(this.settings.muted ? 0 : this.settings.musicVolume);
                    howl.play();
                })
                .catch(error => console.error(`加载音乐失败: ${name}`, error));
            return;
        }
        
        console.log(`播放音乐: ${name}`);
        sound.howl.loop(true);
        sound.howl.volume(this.settings.muted ? 0 : this.settings.musicVolume);
        sound.howl.play();
    }
    
    /**
     * 停止背景音乐
     * @param {string} name 音乐名称
     */
    stopMusic(name) {
        console.log(`尝试停止音乐: ${name}`);
        
        const sound = this.sounds[name];
        
        if (!sound) {
            console.warn(`未找到音乐: ${name}`);
            return;
        }
        
        if (!sound.howl) {
            console.warn(`音乐未加载: ${name}`);
            return;
        }
        
        console.log(`停止音乐: ${name}`);
        sound.howl.stop();
    }
    
    /**
     * 暂停背景音乐
     */
    pauseMusic() {
        if (this.music && this.music.howl) {
            this.music.howl.pause();
        }
    }
    
    /**
     * 恢复背景音乐
     */
    resumeMusic() {
        if (this.settings.muted) return;
        
        if (this.music && this.music.howl) {
            this.music.howl.play();
        }
    }
    
    /**
     * 设置音效音量
     * @param {number} volume 音量 (0-1)
     */
    setSfxVolume(volume) {
        this.settings.sfxVolume = Math.max(0, Math.min(1, volume));
        
        // 更新所有已加载的音效音量
        for (const sound of Object.values(this.sounds)) {
            if (sound.howl) {
                sound.howl.volume(this.settings.muted ? 0 : this.settings.sfxVolume);
            }
        }
        
        this.saveSettings();
    }
    
    /**
     * 设置背景音乐音量
     * @param {number} volume 音量 (0-1)
     */
    setMusicVolume(volume) {
        this.settings.musicVolume = Math.max(0, Math.min(1, volume));
        
        if (this.music && this.music.howl) {
            this.music.howl.volume(this.settings.muted ? 0 : this.settings.musicVolume);
        }
        
        this.saveSettings();
    }
    
    /**
     * 切换静音状态
     * @returns {boolean} 新的静音状态
     */
    toggleMute() {
        this.settings.muted = !this.settings.muted;
        
        // 更新所有已加载的音效音量
        for (const sound of Object.values(this.sounds)) {
            if (sound.howl) {
                sound.howl.volume(this.settings.muted ? 0 : this.settings.sfxVolume);
            }
        }
        
        // 更新背景音乐音量
        if (this.music && this.music.howl) {
            this.music.howl.volume(this.settings.muted ? 0 : this.settings.musicVolume);
        }
        
        this.saveSettings();
        
        return this.settings.muted;
    }
} 